package cn.com.shopec.erp.multiChannel.common;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;

import com.jd.open.api.sdk.DefaultJdClient;
import com.jd.open.api.sdk.JdClient;
import com.jd.open.api.sdk.JdException;
import com.jd.open.api.sdk.domain.order.ItemInfo;
import com.jd.open.api.sdk.domain.order.OrderSearchInfo;
import com.jd.open.api.sdk.domain.order.UserInfo;
import com.jd.open.api.sdk.domain.ware.Ware;
import com.jd.open.api.sdk.request.ware.WareGetRequest;
import com.jd.open.api.sdk.response.ware.WareGetResponse;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.domain.Item;
import com.taobao.api.domain.Order;
import com.taobao.api.domain.Trade;
import com.taobao.api.request.ItemSellerGetRequest;
import com.taobao.api.response.ItemSellerGetResponse;

import cn.com.shopec.erp.common.utils.DateUtil;
import cn.com.shopec.erp.common.utils.StringUtil;
import cn.com.shopec.erp.multiChannel.entity.ChannelOrder;
import cn.com.shopec.erp.multiChannel.entity.ChannelOrderItem;
import cn.com.shopec.erp.multiChannel.entity.ChannelOrderReceiver;
import cn.com.shopec.erp.multiChannel.service.impl.JingDongServiceImpl;

public class MultiChannelConvert {
	private static Logger log = Logger.getLogger(MultiChannelConvert.class);
	
	/**
	 * 京东渠道订单转换
	 * @param orderInfo
	 * @return
	 */
	public static ChannelOrder convertChannelJDOrder(OrderSearchInfo orderInfo){
		ChannelOrder channelOrder=new ChannelOrder();
		channelOrder.setChannelOrderId(orderInfo.getOrderId());
		channelOrder.setChannelOrderType(MultiChannelConstant.JD_MULTI_CHANNEL);
		channelOrder.setOrderState(convertOrderState(orderInfo.getOrderState()));
		channelOrder.setDeliveryState(MultiChannelConstant.CHANNEL_DELIVERY_STATE_NO);	
		channelOrder.setPayState(convertJDPayState(orderInfo.getBalanceUsed()));
		channelOrder.setPayType(convertJDPayType(orderInfo.getPayType()));
		channelOrder.setOrderType(convertJDOrderType(orderInfo.getReturnOrder()));
		channelOrder.setOrderTotalPrice(Double.parseDouble(orderInfo.getOrderPayment()));
		channelOrder.setOrderStartTime(orderInfo.getOrderStartTime());
		channelOrder.setReturnOrder(orderInfo.getReturnOrder());
		channelOrder.setOrderRemark(orderInfo.getOrderRemark());
		channelOrder.setReceiverName(orderInfo.getConsigneeInfo().getFullname());
		channelOrder.setReceiverPhone(orderInfo.getConsigneeInfo().getMobile()==null?orderInfo.getConsigneeInfo().getTelephone():orderInfo.getConsigneeInfo().getMobile());
		return channelOrder;
	}
	
	/**
	 * 淘宝渠道订单转换
	 * @param orderInfo
	 * @return
	 */
	public static ChannelOrder convertChannelTBOrder(Trade trade){
		ChannelOrder channelOrder=new ChannelOrder();
		channelOrder.setChannelOrderId(trade.getTid().toString());
		channelOrder.setChannelOrderType(convertTBOrderType(trade.getType()));
		channelOrder.setOrderState(convertOrderState(trade.getStatus()));
		channelOrder.setDeliveryState(MultiChannelConstant.CHANNEL_DELIVERY_STATE_NO);	
		channelOrder.setPayState(convertTBPayState(trade.getPayTime()));
		channelOrder.setPayType(MultiChannelConstant.JD_PAY_STATE_FOUR);
		channelOrder.setOrderType(null);
		channelOrder.setOrderTotalPrice(Double.parseDouble(trade.getPayment()));
		channelOrder.setOrderStartTime(DateUtil.formatTimesTampDate(trade.getCreated()));
		channelOrder.setReturnOrder(null);
		channelOrder.setOrderRemark(trade.getBuyerMemo());
		channelOrder.setReceiverName(trade.getReceiverName());
		channelOrder.setReceiverPhone(trade.getReceiverMobile()==null?trade.getReceiverPhone():trade.getReceiverMobile());
		return channelOrder;
	}
	
	/**
	 * 京东渠道订单商品转换
	 * @param orderInfo
	 * @return
	 */
	public static List<ChannelOrderItem> convertChannelJDOrderItem(OrderSearchInfo orderInfo){
		List<ChannelOrderItem> items=new ArrayList<ChannelOrderItem>();
		for (ItemInfo into : orderInfo.getItemInfoList()) {
			try {
				ChannelOrderItem item=new ChannelOrderItem();
				item.setChannelOrderId(orderInfo.getOrderId());
				item.setSkuId(into.getSkuId());
				item.setSkuName(into.getSkuName());
				item.setItemPrice(Double.parseDouble(into.getJdPrice()));
				item.setItemTotal(Double.parseDouble(into.getItemTotal()));
				Ware ware=queryJDWare(into.getWareId());
				item.setItemNum(ware==null?"":ware.getItemNum());
				items.add(item);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return items;
	}
	
	/**
	 * 订单商品中没有返回货品号码，调用接口单独查询商品取得货品号码(京东接口缺陷)
	 * @param wareId
	 * @return
	 */
	public static Ware queryJDWare(String wareId){
		log.info("queryJDWare request wareId is = "+wareId);
		Ware ware=null;
		String serverUrl=MultiChannelConfig.getString("jd.serverUrl");
		String accessToken=MultiChannelConfig.getString("jd.accessToken");
		String appKey=MultiChannelConfig.getString("jd.appKey");
		String appSecret=MultiChannelConfig.getString("jd.appSecret");
		JdClient client=new DefaultJdClient(serverUrl,accessToken,appKey,appSecret); 
		WareGetRequest request=new WareGetRequest();
		request.setWareId(wareId);
		try {
			WareGetResponse rsp = client.execute(request);
			log.info("WareGetResponse result ZhDesc is = "+rsp.getZhDesc()+",code is = "+rsp.getCode());
			if(MultiChannelConstant.JD_RESULT_CODE.equals(rsp.getCode())) {
				ware=rsp.getWare();
			}
		} catch (JdException e) {
			e.printStackTrace();
		}
		log.info("queryJDWare result ware is = "+ware+",ware get itemNum is "+ware.getItemNum());
		return ware;
	}
	
	/**
	 * 淘宝渠道订单商品转换
	 * @param orderInfo
	 * @return
	 */
	public static List<ChannelOrderItem> convertChannelTBOrderItem(Trade trade){
		List<ChannelOrderItem> items=new ArrayList<ChannelOrderItem>();
		ChannelOrderItem item=new ChannelOrderItem();
		for (Order info : trade.getOrders()) {
			Item queryItem=queryTBItem(info.getNumIid());
			item.setChannelOrderId(trade.getTid().toString());
			item.setSkuId(info.getSkuId());
			item.setSkuName(queryItem.getTitle());
			item.setItemPrice(Double.parseDouble(info.getPrice()));
			item.setItemTotal(info.getNum().doubleValue());
			item.setItemNum(queryItem==null?"":queryItem.getOuterId());
			items.add(item);
		}
		return items;
	}
	
	/**
	 * 订单商品中没有返回商家编码，调用接口单独查询商品取得商家编码(淘宝接口缺陷)
	 * @param wareId
	 * @return
	 */
	public static Item queryTBItem(Long numIId){
		log.info("queryTBItem request numIId is = "+numIId);
		Item item=null;
		String serverUrl=MultiChannelConfig.getString("tb.serverUrl");
		String accessToken=MultiChannelConfig.getString("tb.accessToken");
		String appKey=MultiChannelConfig.getString("tb.client_id");
		String appSecret=MultiChannelConfig.getString("tb.client_secret");
		TaobaoClient client = new DefaultTaobaoClient(serverUrl, appKey, appSecret);
		ItemSellerGetRequest req = new ItemSellerGetRequest();
		req.setFields("outer_id");
		req.setFields("title");
		req.setNumIid(numIId);
		try {
			ItemSellerGetResponse rsp= client.execute(req, accessToken);
			log.info("ItemSellerGetResponse result ZhDesc is = "+rsp.getBody()+",code is = "+rsp.getErrorCode());
			if(!StringUtil.isEmpty(rsp.getBody()) && rsp.getItem()!=null) {
				item=rsp.getItem();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		log.info("queryTBWare result item is = "+item+",ware get OuterId is "+item.getOuterId());
		return item;
	}
	
	/**
	 * 京东渠道订单收货人转换
	 * @param orderInfo
	 * @return
	 */
	public static ChannelOrderReceiver convertChannelJDOrderReceiver(OrderSearchInfo orderInfo){
		ChannelOrderReceiver receiver=new ChannelOrderReceiver();
		UserInfo info=orderInfo.getConsigneeInfo();
		receiver.setChannelOrderId(orderInfo.getOrderId());
		receiver.setFullname(info.getFullname());
		receiver.setTelephone(info.getTelephone());
		receiver.setMobile(info.getMobile());
		receiver.setProvince(info.getProvince());
		receiver.setCity(info.getCity());
		receiver.setCounty(info.getCounty());
		receiver.setFullAddress(info.getFullAddress());
		return receiver;
	}
	
	/**
	 * 淘宝渠道订单收货人转换
	 * @param orderInfo
	 * @return
	 */
	public static ChannelOrderReceiver convertChannelTBOrderReceiver(Trade trade){
		ChannelOrderReceiver receiver=new ChannelOrderReceiver();
		receiver.setChannelOrderId(trade.getTid().toString());
		receiver.setFullname(trade.getReceiverName());
		receiver.setTelephone(trade.getReceiverPhone());
		receiver.setMobile(trade.getReceiverMobile());
		receiver.setProvince(trade.getReceiverState());
		receiver.setCity(trade.getReceiverCity());
		receiver.setCounty(trade.getReceiverCountry());
		receiver.setFullAddress(trade.getReceiverAddress());
		return receiver;
	}
	
	/**
	 * 转换订单状态
	 * @param valueState
	 * @return
	 */
	public static String convertOrderState(String valueState){
		String state="";
		//JD订单状态转换
		switch (valueState) {
			//京东订单状态转换
			case MultiChannelConstant.JD_TRADE_STATE_SEND:
			case MultiChannelConstant.JD_TRADE_STATE_RECEIVED:
			case MultiChannelConstant.JD_TRADE_STATE_RECEIVE_CONFIRM:
				state=MultiChannelConstant.CHANNEL_ORDER_STATE_DELIVERY_OK;
				break;
			case MultiChannelConstant.JD_TRADE_STATE_OUT:
			case MultiChannelConstant.JD_TRADE_STATE_WAIT_DELIVERY:
				state=MultiChannelConstant.CHANNEL_ORDER_STATE_WAIT_DELIVERY;
				break;
			case MultiChannelConstant.JD_TRADE_STATE_RECEIPTS_CONFIRM:
			case MultiChannelConstant.JD_TRADE_STATE_FINISHED:
				state=MultiChannelConstant.CHANNEL_ORDER_STATE_OK;
				break;
			case MultiChannelConstant.JD_TRADE_STATE_CANCELED:
				state=MultiChannelConstant.CHANNEL_ORDER_STATE_CANCEL;
				break;
			case MultiChannelConstant.JD_TRADE_STATE_LOCKED:
				state=MultiChannelConstant.CHANNEL_ORDER_STATE_LOCKED;
				break;
				
			//淘宝订单状态转换
			case MultiChannelConstant.TB_TRADE_STATE_CONSIGNED_PART:
				state=MultiChannelConstant.CHANNEL_ORDER_STATE_LITTER_DELIVERY;
				break;
			case MultiChannelConstant.TB_TRADE_STATE_CONFIRM_GOODS:
				state=MultiChannelConstant.CHANNEL_ORDER_STATE_DELIVERY_OK;
				break;
			case MultiChannelConstant.TB_TRADE_STATE_BUYER_SIGNED:
				state=MultiChannelConstant.CHANNEL_ORDER_STATE_CONFIRM_DELIVERY;
				break;
			case MultiChannelConstant.TB_TRADE_STATE_FINISHED:
				state=MultiChannelConstant.CHANNEL_ORDER_STATE_OK;
				break;
			case MultiChannelConstant.TB_TRADE_STATE_CLOSED:
			case MultiChannelConstant.TB_TRADE_STATE_CLOSED_BY_TAOBAO:
			case MultiChannelConstant.TB_TRADE_STATE_ALL_CLOSED:
				state=MultiChannelConstant.CHANNEL_ORDER_STATE_CLOSED;
				break;
			case MultiChannelConstant.TB_TRADE_STATE_WAIT_PAY:
			case MultiChannelConstant.TB_TRADE_STATE_CREATE_PAY:
			case MultiChannelConstant.TB_TRADE_STATE_PENDING:
			case MultiChannelConstant.TB_TRADE_STATE_ALL_WAIT_PAY:
				state=MultiChannelConstant.CHANNEL_ORDER_STATE_WAIT_PAY;
				break;
			case MultiChannelConstant.TB_TRADE_STATE_SEND_GOODS:
			case MultiChannelConstant.TB_TRADE_STATE_AUTH_CONFIRM:
				state=MultiChannelConstant.CHANNEL_ORDER_STATE_WAIT_DELIVERY;
				break;
		}
		return state;
	}
	
	/**
	 * 转换京东支付类型
	 * @param valueState
	 * @return
	 */
	public static String convertJDPayType(String valueType){
		//valueType:4-在线支付
		String type="";
		if(valueType.indexOf("-")>0){
			type=valueType.split("-")[0];
		}
		return type;
	}
	
	/**
	 * 转换京东订单类型
	 * @param balanceUsed
	 * @return
	 */
	private static String convertJDOrderType(String returnOrder) {
		//售后订单标记==0？白拿:返还
		String orderType=returnOrder.equals(MultiChannelConstant.JD_RETURN_ORDER_NO)?MultiChannelConstant.CHANNEL_ORDER_TYPE_GET:MultiChannelConstant.CHANNEL_ORDER_TYPE_RETURN;
		return orderType;
	}
	
	/**
	 * 转换京东支付状态
	 * @param balanceUsed
	 * @return
	 */
	private static String convertJDPayState(String balanceUsed) {
		//余额支付金额>0?未支付:已支付
		String payState="";
		if(balanceUsed!=null && !balanceUsed.equals("")){
			payState=Double.parseDouble(balanceUsed)>0?MultiChannelConstant.CHANNEL_PAY_STATE_NO:MultiChannelConstant.CHANNEL_PAY_STATE_YES;
		}
		return payState;
	}
	
	/**
	 * 转换淘宝支付状态
	 * @param balanceUsed
	 * @return
	 */
	private static String convertTBPayState(Date payTime) {
		//payTime==null?未支付:已支付
		String payState=(payTime==null?MultiChannelConstant.CHANNEL_PAY_STATE_NO:MultiChannelConstant.CHANNEL_PAY_STATE_YES);
		return payState;
	}
	
	/**
	 * 转换淘宝订单类型
	 * @param balanceUsed
	 * @return
	 */
	private static String convertTBOrderType(String orderType) {
		//type.contains('tmall_i18n')?2:1
		String type=orderType.contains(MultiChannelConstant.TM_CHANNEL_TYPE)?MultiChannelConstant.TM_MULTI_CHANNEL:MultiChannelConstant.TB_MULTI_CHANNEL;
		return type;
	}
}
